package com.lwj.liwanjia.view.fragment.search;


import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.DrawableUtils;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;

import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.HistorySearchAdapter;
import com.lwj.liwanjia.base.BaseFragment;
import com.lwj.liwanjia.bean.LitepalBean;
import com.lwj.liwanjia.bean.ResouBean;
import com.lwj.liwanjia.impl.ResouView;
import com.lwj.liwanjia.presenter.ResouPresenter;
import com.lwj.liwanjia.utils.RxBus;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.utils.ZFlowLayout;
import com.lwj.liwanjia.view.activity.search.SearchActivity;
import com.superrecycleview.superlibrary.adapter.SuperBaseAdapter;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 搜索历史
 */
public class SearchHistoryFragment extends BaseFragment implements ResouView {

    @BindView(R.id.flowLayout)
    ZFlowLayout flowLayout;
    @BindView(R.id.history_search)
    SuperRecyclerView historySearch;

    private HistorySearchAdapter adapter;
    private List<LitepalBean> historyList = new ArrayList<>();
    private View header, footer;
    private SearchActivity activity;
    private EditText search;
    private ResouPresenter resouPresenter;//搜索热词
    private String token;
    private String type;
    private Subscription subscription;


    @Override
    protected void initView(View view) {
        activity = (SearchActivity) getActivity();
        search = activity.getSearch();
        type = activity.getType();
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        historySearch.setLayoutManager(manager);
        historySearch.setRefreshEnabled(false);
        historySearch.setLoadMoreEnabled(false);
        adapter = new HistorySearchAdapter(getActivity(), historyList);
        addView();
        historySearch.setAdapter(adapter);
        token = SpfUtils.getSpfUtils(getActivity()).getToken();
        resouPresenter = new ResouPresenter(this);
        clickListener();
        subscription = RxBus.getInstance().toObserverable(String.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (s.equals("店铺")) {
                    resouPresenter.getResouData(token, "店铺");
                } else if (s.equals("宝贝")) {
                    resouPresenter.getResouData(token, "宝贝");
                }
            }
        });
    }

    //添加头部和尾部
    private void addView() {
        header = LayoutInflater.from(getActivity()).inflate(R.layout.header_footer_layout, null);
        TextView tv_header = (TextView) header.findViewById(R.id.tv_clear);
        tv_header.setText("搜索历史");
        tv_header.setTextColor(getResources().getColor(R.color.colorCECECE));

        footer = LayoutInflater.from(getActivity()).inflate(R.layout.header_footer_layout, null);
        TextView tv_clear = (TextView) footer.findViewById(R.id.tv_clear);
        //清空
        tv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                historyList.clear();
                adapter.notifyDataSetChanged();
                adapter.removeFooterView(footer);
                adapter.removeHeaderView(header);
                //清空本地数据库
                DataSupport.deleteAll(LitepalBean.class);
            }
        });
        selectHistory();
    }

    //查询数据库中的数据
    private void selectHistory() {
        historyList.clear();
        //查询数据库中是否有数据
        List<LitepalBean> all = DataSupport.findAll(LitepalBean.class);
        if (all.size() > 0) {
            adapter.addHeaderView(header);
            adapter.addFooterView(footer);
            for (int i = all.size() - 1; i >= 0; i--) {
                historyList.add(all.get(i));
            }
            adapter.notifyDataSetChanged();
        } else {
            //清除头部和尾部
            adapter.removeFooterView(footer);
            adapter.removeHeaderView(header);
        }
    }

    //点击事件
    private void clickListener() {
        //搜索历史点击事件
        adapter.setOnItemClickListener(new SuperBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object item, int position) {
                search.setText(historyList.get(position).getHistoryName());
                search.setSelection(search.getText().toString().length());
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            adapter.removeFooterView(footer);
            adapter.removeHeaderView(header);
            selectHistory();
        }
    }

    // 初始化标签
    @SuppressWarnings("ResourceType")
    private void initLabel(List<String> data) {
        flowLayout.removeAllViews();
        MarginLayoutParams lp = new MarginLayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 30;
        lp.bottomMargin = 20;
        for (int i = 0; i < data.size(); i++) {
            final TextView tag = new TextView(getActivity());
            tag.setText(data.get(i));
            tag.setTextColor(getResources().getColor(R.color.color6D6D6D));
            tag.setTextSize(14);
            tag.setBackgroundDrawable(getResources().getDrawable(R.drawable.lable_item_bg_normal));
            //标签点击事件
            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LitepalBean litepal = new LitepalBean();
                    String historyName = tag.getText().toString();
                    search.setText(historyName);
                    search.setSelection(historyName.length());
                    litepal.setHistoryName(historyName);
                    //判断数据库中是否已存在该数据，没有就存储
                    List<LitepalBean> beanList = DataSupport.where("historyName=?", historyName).find(LitepalBean.class);
                    if (beanList.size() == 0) {
                        //更新集合
                        historyList.add(litepal);
                        if (historyList.size() <= 1) {
                            adapter.addHeaderView(header);
                            adapter.addFooterView(footer);
                        }
                        adapter.notifyDataSetChanged();
                        //更新数据库
                        litepal.save();
                    }
                }
            });
            flowLayout.addView(tag, lp);
        }
    }

    @Override
    protected void initData() {
        resouPresenter.getResouData(token, type);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_search_history;
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(getActivity(), "数据加载失败", Toast.LENGTH_SHORT).show();
    }

//    获取热搜标签
    @Override
    public void getResouData(ResouBean resouBean) {
        if (resouBean.getState() == 0) {
            Toast.makeText(getActivity(), "接口有误", Toast.LENGTH_SHORT).show();
        } else if (resouBean.getState() == 1) {
            List<String> data = resouBean.getData();
            initLabel(data);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }
}
